<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2020/2/19
 * Time: 18:03
 */
namespace app\api\controller;
use think\Db;

class My extends Base
{
    private $user_id; // 用户ID
    private $page; // 页码
    private $create_time;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status' => 301, 'msg' => $this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    
    /**
     * 用户基本信息
     * @return \think\response\Json
     * type   1 “我的”页面展示信息    2 我的信息
     */
    public function showBase(){
        $type = input('type') ? input('type') : 3; // 1 “我的”页面基础信息   2 我的信息   3 “我的”页面二级页面信息
        $query = Db::table('up_u_user')->where('user_id', $this->user_id);
        if($type == 1){ // “我的”页面信息
            $data = $query->field([
                'user_image',
                'user_username',
                'user_total_balance',
                'user_phone',
                'user_bo_fy_balance',
                'user_code',
                'user_giftbag_level',
                'user_rule',
                'user_bo_district_role',
                'user_bo_role',
                'user_up_tz_code',
                'user_ty_code',
                'user_tz_code',
                'user_up_up_tz_code',
                'user_bo_total_balance',
                'user_recharge_balance',
                'user_bo_balance',
                'user_stock_role',
                'user_system_show',
                'user_giftbag_show',
                'user_dl_show',
                'user_big_rule'
            ])
                ->find();
            if($data['user_bo_role'] == 3){
                $userCode = $data['user_up_tz_code'] . '_' . $data['user_ty_code'];
            }elseif($data['user_bo_role'] == 4){
                $userCode = $data['user_tz_code'];
                $userCode .= $data['user_up_tz_code'] == -1 ? '' : '_' . $data['user_up_tz_code'];
                $userCode .= $data['user_up_up_tz_code'] == -1 ? '' : '_' . $data['user_up_up_tz_code'];
            }else{
                $userCode = '/';
            }
            $data['userCode'] = $userCode;
            $data['user_bo_district_role'] = explode(',', trim($data['user_bo_district_role'], ','));

            // 订单信息
            $data['unpay_num'] = $this->myOrder(1, 2); // 待付款订单数量
            $data['pay_num'] = $this->myOrder(2, 2); // 待发货订单数量
            $data['unget_num'] = $this->myOrder(3, 2); // 待收货订单数量
            $data['over_num'] = $this->myOrder(4, 2); // 已完成订单数量
        }elseif($type == 2){
            $data = $query->join('up_area a1', 'a1.district_id = user_sheng', 'LEFT')
                ->join('up_area a2', 'a2.district_id = user_shi', 'LEFT')
                ->join('up_area a3', 'a3.district_id = user_qu', 'LEFT')
                ->field('user_image, user_username, user_real_name, user_gender, user_phone, user_address, 
                user_sheng, user_shi, user_qu, a1.district sheng, a2.district shi, a3.district qu, 
                user_shop_name, user_bank_username, user_bank_name, user_bankcard_code')
                ->find();
        }else{
            $data = $query->field('user_image, user_username, user_role, user_total_balance, user_invite, 
            user_phone, user_recharge_balance, user_is_perfect, user_giftbag_level, user_bo_role, user_rule')->find();
            // 我的团队
            if($data['user_invite']){
                $data['team_balance'] = $this->myTeam(2, $data['user_invite']);
            }else{
                $data['team_balance'] = [];
            }
            // 订单信息
            $data['unpay_num'] = $this->myOrder(1, 2); // 待付款订单数量
            $data['pay_num'] = $this->myOrder(2, 2); // 待发货订单数量
            $data['unget_num'] = $this->myOrder(3, 2); // 待收货订单数量
            $data['over_num'] = $this->myOrder(4, 2); // 已完成订单数量
        }
        return json(['status' => 200, 'msg' => $data]);
    }

    /**
     * 返回用户积分
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userBalance(){
        $data = Db::table('up_u_user')
            ->where('user_id', $this->user_id)
            ->field('user_recharge_balance, user_big_balance, user_bo_balance')
            ->find();
        return json(['status' => 200, 'msg' => $data]);
    }
    
    /**
     * 用户的角色和权限
     * @return \think\response\Json
     */
    public function userRoleAndRule(){
        $rule = $this->userRule($this->user_id);
        return json(['status' => 200, 'rule' => $rule]);
    }
    
    /**
     * 编辑用户信息
     * @return \think\response\Json
     * user_username      昵称
     * user_image         头像
     */
    public function updateUserInfo(){
        $user_username = input('user_username');
        $user_image = input('user_image');
        $update = [];
        if(isset($user_username) && $user_username != '') $update['user_username'] = $user_username;
        if(isset($user_image) && $user_image != '') $update['user_image'] = $user_image;
        $res = Db::table('up_u_user')->where('user_id', $this->user_id)->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '编辑成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 我的收货地址列表
     * @return \think\response\Json
     */
    public function myAddress(){
        $where['addr_user_id'] = $this->user_id;
        $where['addr_del'] = 1;
        $where['addr_from'] = 2;
        $list = $this->address(1, $where);
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 添加收货地址
     * @return \think\response\Json
     * addr_user_name        收货人
     * addr_user_phone       手机号
     * addr_sheng            省ID
     * addr_shi              市ID
     * addr_qu               区ID
     * addr_address          详细地址
     * addr_is_default       是否是默认地址   1 默认   2 非默认
     */
    public function addAddr(){
        $addr_user_name = input('addr_user_name');
        $addr_user_phone = input('addr_user_phone');
        $addr_sheng = input('addr_sheng');
        $addr_shi = input('addr_shi');
        $addr_qu = input('addr_qu');
        $addr_address = input('addr_address');
        $addr_is_default = input('addr_is_default'); // 1 默认   2 非默认
        
        $where['addr_user_id'] = $this->user_id;
        $where['addr_del'] = 1;
        $where['addr_from'] = 2;
        $address_num = $this->address(3, $where);
        if($address_num >= 20) return json(['status' => 0, 'msg' => '收货地址不可超过20条']);
        
        $insert = [
            'addr_user_id' => $this->user_id,
            'addr_user_name' => $addr_user_name,
            'addr_user_phone' => $addr_user_phone,
            'addr_sheng' => $addr_sheng,
            'addr_shi' => $addr_shi,
            'addr_qu' => $addr_qu,
            'addr_address' => $addr_address,
            'addr_is_default' => $addr_is_default,
            'addr_time' => $this->create_time,
            'addr_from' => 2
        ];
        if($address_num == 0) $insert['addr_is_default'] = 1;
        
        Db::startTrans();
        try{
            // 如果是默认地址，则需先将所有地址设置成非默认
            if($addr_is_default == 1){
                Db::table('up_user_address')
                    ->where('addr_user_id', $this->user_id)
                    ->where('addr_is_default', 1)
                    ->where('addr_from', 2)
                    ->setField('addr_is_default', 2);
            }
            $addr_id = Db::table('up_user_address')->insertGetId($insert);
            Db::commit();
            return json(['status' => 200, 'msg' => $addr_id]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 收货地址详情
     * @return \think\response\Json
     * addr_id     收货地址ID
     */
    public function showAddr(){
        $addr_id = input('addr_id');
        $where['addr_del'] = 1;
        if(isset($addr_id) && $addr_id != ''){ // 展示收货地址
            $where['addr_id'] = $addr_id;
        }else{ // 展示默认收货地址
            $where['addr_user_id'] = $this->user_id;
            $where['addr_is_default'] = 1;
        }
        $info = $this->address(2, $where);
        if($info){
            return json(['status' => 200, 'msg' => $info]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 花样青青用户展示默认收货地址
     * @return \think\response\Json
     */
    public function showQqAddr(){
        $where['addr_user_id'] = $this->user_id;
        $where['addr_from'] = 1;
        $where['addr_del'] = 1;
        $info = $this->address(2, $where);
        if($info){
            return json(['status' => 200, 'msg' => $info]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 默认收货地址
     * @return \think\response\Json
     */
    public function defaultAddr(){
        $where['addr_user_id'] = $this->user_id;
        $where['addr_is_default'] = 1;
        $where['addr_del'] = 1;
        $where['addr_from'] = 2;
        $info = $this->address(1, $where);
        if($info){
            return json(['status' => 200, 'msg' => $info]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 编辑收货地址
     * @return \think\response\Json
     * addr_id               收货地址ID
     * addr_user_name        收货人
     * addr_user_phone       手机号
     * addr_sheng            省ID
     * addr_shi              市ID
     * addr_qu               区ID
     * addr_address          详细地址
     * addr_is_default       是否是默认地址   1 默认   2 非默认
     */
    public function updateAddr(){
        $addr_id = input('addr_id');
        $addr_user_name = input('addr_user_name');
        $addr_user_phone = input('addr_user_phone');
        $addr_sheng = input('addr_sheng');
        $addr_shi = input('addr_shi');
        $addr_qu = input('addr_qu');
        $addr_address = input('addr_address');
        $addr_is_default = input('addr_is_default'); // 1 默认   2 非默认
    
        $update = [
            'addr_user_name' => $addr_user_name,
            'addr_user_phone' => $addr_user_phone,
            'addr_sheng' => $addr_sheng,
            'addr_shi' => $addr_shi,
            'addr_qu' => $addr_qu,
            'addr_address' => $addr_address,
            'addr_is_default' => $addr_is_default,
            'addr_updatetime' => $this->create_time
        ];
        $default = Db::table('up_user_address')->where('addr_id', $addr_id)->value('addr_is_default');
        Db::startTrans();
        try{
            // 如果是默认地址，则需先将所有地址设置成非默认
            if($addr_is_default == 1 && $default == 2){
                Db::table('up_user_address')
                    ->where('addr_user_id', $this->user_id)
                    ->where('addr_is_default', 1)
                    ->where('addr_from', 2)
                    ->setField('addr_is_default', 2);
            }
            Db::table('up_user_address')->where('addr_id', $addr_id)->update($update);
            Db::commit();
            return json(['status' => 200, 'msg' => '编辑成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 删除收货地址
     * @return \think\response\Json
     * addr_id       收货地址ID
     */
    public function delAddr(){
        $addr_id = input('addr_id');
        $addr_default = Db::table('up_user_address')->where('addr_id', $addr_id)->value('addr_is_default');
        $where['addr_user_id'] = $this->user_id;
        $where['addr_del'] = 1;
        $where['addr_from'] = 2;
        $addr = $this->address(3, $where);
        if($addr == 1){
            return json(['status' => 0, 'msg' => '最少要留一个收货地址']);
        }
    
        Db::startTrans();
        try{
            // 删除该条记录
            Db::table('up_user_address')->where('addr_id', $addr_id)->setField('addr_del', 2);
            if($addr_default == 1){ // 如果删除的是默认地址
                $where['addr_is_default'] = 2;
                $addr_new = $this->address(1, $where);
                Db::table('up_user_address')->where('addr_id', $addr_new[0]['addr_id'])->setField('addr_is_default', 1);
            }
            
            Db::commit();
            return json(['status' => 200, 'msg' => '删除成功']);
        }catch(\Exception $e){
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 设置默认发货地址
     * @return \think\response\Json
     * addr_id      ID
     */
    public function setDefault(){
        $addr_id = input('addr_id');
        $default = Db::table('up_user_address')->where('addr_id', $addr_id)->value('addr_is_default');
        if($default == 1){
            return json(['status' => 200, 'msg' => '设置成功']);
        }else{
            Db::startTrans();
            try{
                Db::table('up_user_address')
                    ->where('addr_user_id', $this->user_id)
                    ->where('addr_is_default', 1)
                    ->where('addr_from', 2)
                    ->setField('addr_is_default', 2);
                Db::table('up_user_address')->where('addr_id', $addr_id)->setField('addr_is_default', 1);
                Db::commit();
                return json(['status' => 200, 'msg' => '设置成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        }
    }
    
    /**
     * 常见问题
     * @return \think\response\Json
     */
    public function commonProblem(){
        $problem = Db::table('up_problem')
            ->field('problem_id, problem_title, problem_content')
            ->order('problem_time desc')
            ->select();
        if($problem){
            return json(['status' => 200, 'msg' => $problem]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 意见反馈
     * @return \think\response\Json
     * feedback_content       反馈内容
     * feedback_phone         手机号
     */
    public function feedback(){
        $feedback_content = input('feedback_content');
        $feedback_phone = input('feedback_phone');
        $insert = [
            'fd_user_id' => $this->user_id,
            'fd_content' => $feedback_content,
            'fd_phone' => $feedback_phone,
            'fd_time' => $this->create_time
        ];
        $res = Db::table('up_feedback')->insert($insert);
        if($res){
            return json(['status' => 200, 'msg' => '提交成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }
    
    /**
     * 联系我们
     * @return \think\response\Json
     */
    public function callUs(){
        $data = Db::table('up_about')->where('id', 3)->field('service_phone, black_image')->find();
        return json(['status' => 200, 'msg' => $data]);
    }
    
    /**
     * 关于我们
     * @return \think\response\Json
     * type      类型   4 功能介绍   5 法律声明   6 平台协议
     */
    public function aboutUs(){
        $type = input('type'); // 4 功能介绍  5 法律声明  6 平台协议
        $about = Db::table('up_about')->where('id', $type)->value('content');
        return json(['status' => 200, 'msg' => $about]);
    }































    /**
     * 分销
     * @return \think\response\Json
     */
    public function fenXiao(){
        $fenxiao = Db::table('up_u_user')
            ->where('user_id', $this->user_id)
            ->field('user_invite, user_invite_qrcode')
            ->find();
        return json(['status' => 200, 'msg' => $fenxiao]);
    }
    
    /**
     * 我的团队
     * @return \think\response\Json
     */
    public function myTeamList(){
        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_invite')->find();
        if($user['user_invite']){
            $teamList = $this->myTeam(1, $user['user_invite']);
        }else{
            $teamList = 0;
        }
        if($teamList){
            return json(['status' => 200, 'msg' => $teamList]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 我的团队---我的基本信息
     * @return \think\response\Json
     */
    public function mySelfTeamInfo(){
        $user = Db::table('up_u_user')
            ->field('user_id, user_image, user_real_name, user_phone, user_total_fy_balance')
            ->where('user_id', $this->user_id)
            ->find();
        return json(['status' => 200, 'msg' => $user]);
    }
    
    /**
     * 我的团队---我的下级用户信息
     * @return \think\response\Json
     * other_user_id     下级用户ID
     */
    public function otherUserFy(){
        $other_user_id = input('other_user_id');
        $other_user = Db::table('up_u_user')
            ->field('user_id, user_image, user_real_name, user_phone')
            ->where('user_id', $other_user_id)
            ->find();
        // 为我带来的总积分
        $total = Db::table('up_integral')
            ->where('inte_other_user_id', $other_user_id)
            ->where('inte_user_id', $this->user_id)
            ->where('inte_type', 3)
            ->where('inte_status', 1)
            ->sum('inte_number');
        $other_user['get_total_balance'] = $total;
        return json(['status' => 200, 'msg' => $other_user]);
    }

    
    /**
     * 我的订单列表
     * @return \think\response\Json
     * order_status    0 全部  1 待付款  2 待发货  3 待收货  4 已完成
     * page            页码
     */
    public function orderList(){
        $order_status = input('order_status'); // 0 全部  1 待付款  2 待发货  3 待收货  4 已完成
        $list = $this->myOrder($order_status, 1);
        if($list){
            foreach($list as $k => $v){
                $list[$k]['order_goods'] = Db::table('up_order_info')
                    ->where('oi_order_id', $v['order_id'])
                    ->field('oi_goods_id, oi_goods_price, oi_num, oi_goods_thumb, oi_goods_name, oi_goods_spec')
                    ->select();
            }
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 修改地址
     * @return \think\response\Json
     * order_addr_id     收货地址ID
     * order_id          订单ID
     */
    public function changeAddr(){
        $order_addr_id = input('order_addr_id');
        $order_id = input('order_id');
        // 收货地址信息
        $address = Db::table('up_user_address')
            ->where('addr_id', $order_addr_id)
            ->field('addr_user_name, addr_user_phone, addr_sheng, addr_shi, addr_qu, addr_address')
            ->find();
        
        $res = Db::table('up_order')->where('order_id', $order_id)
            ->update([
                'order_addr_id' => $order_addr_id,
                'order_sheng' => $address['addr_sheng'],
                'order_shi' => $address['addr_shi'],
                'order_qu' => $address['addr_qu'],
                'order_address' => $address['addr_address'],
                'order_receive_username' => $address['addr_user_name'],
                'order_receive_phone' => $address['addr_user_phone']
            ]);
        if($res){
            return json(['status' => 200, 'msg' => '修改成功']);
        }else{
            return json(['status' => 0, 'msg' => '修改失败']);
        }
    }
    
    /**
     * 取消订单
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function cancelOrder(){
        $order_id = input('order_id');
        $order_goods = Db::table('up_order_info')->where('oi_order_id', $order_id)->field('oi_goods_id, oi_num')->select();
        Db::startTrans();
        try{
            // 修改订单状态
            Db::table('up_order')
                ->where('order_id', $order_id)
                ->update(['order_status' => 6, 'order_cancel_time' => $this->create_time]);
            
            foreach($order_goods as $k => $v){
                // 释放库存
                Db::table('up_goods')->where('goods_id', $v['oi_goods_id'])->setInc('goods_stock', $v['oi_num']);
                // 减销量
                Db::table('up_goods')->where('goods_id', $v['oi_goods_id'])->setDec('goods_sale_num', $v['oi_num']);
            }
            Db::commit();
            return json(['status' => 200, 'msg' => '取消成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 关闭订单---30分钟未支付
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function closeOrder(){
        $order_id = input('order_id');
        $order = Db::table('up_order')->whereTime('order_id', $order_id)->field('order_status')->find();
        if($order['order_status'] == 1){
            Db::startTrans();
            try{
                // 修改状态
                Db::table('up_order')->where('order_id', $order_id)->update(['order_status' => 5, 'order_close_time' => date('Y-m-d H:i:s')]);
        
                $order_goods = Db::table('up_order_info')->where('oi_order_id', $order_id)->field('oi_goods_id, oi_num')->select();
                foreach($order_goods as $kk => $vv){
                    // 释放库存
                    Db::table('up_goods')->where('goods_id', $vv['oi_goods_id'])->setInc('goods_stock', $vv['oi_num']);
                    // 减销量
                    Db::table('up_goods')->where('goods_id', $vv['oi_goods_id'])->setDec('goods_sale_num', $vv['oi_num']);
                }
                Db::commit();
                return json(['status' => 200, 'msg' => true]);
            }catch(\Exception $e){
                Db::rollback();
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        }else{
            return json(['status' => 200, 'msg' => true]);
        }
        
    }
    
    /**
     * 付款---暂未使用
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function orderPay(){
        $order_id = input('order_id');

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);

        $userRule = $this->userRule($this->user_id);
        if($userRule == '1' || $userRule == '3') return json(['status' => 0, 'msg' => '权限不足']);

        $order = Db::table('up_order')
            ->join('up_u_user', 'user_id = order_user_id', 'LEFT')
            ->where('order_id', $order_id)
            ->field('order_total_price, user_recharge_balance, user_other_balance, order_user_id, order_status')
            ->find();
        if($order['order_total_price'] > $order['user_recharge_balance']) return json(['status' => 222, 'msg' => '可用积分不足']);
    
        // 用于更新用户剩余积分的数组
//        $update_price = $this->decPrice($order);
        $update_price['user_recharge_balance'] = $order['user_recharge_balance'] - $order['order_total_price'];
    
        if($order['order_status'] == 1){
            Db::startTrans();
            try{
                // 更新订单表
                $update = [
                    'order_pay_type' => 1,
                    'order_status' => 2,
                    'order_pay_time' => $this->create_time
                ];
                Db::table('up_order')->where('order_id', $order_id)->update($update);
                // 更新用户余额
                Db::table('up_u_user')->where('user_id', $order['order_user_id'])->update($update_price);
                // 积分明细
                $integral = [
                    'inte_user_id' => $order['order_user_id'],
                    'inte_other_user_id' => 0,
                    'inte_type' => 2,
                    'inte_des' => '购买商品-消费',
                    'inte_number' => $order['order_total_price'],
                    'inte_time' => $this->create_time,
                    'inte_front' => $order['user_recharge_balance'],
                    'inte_after' => $update_price['user_recharge_balance'],
                    'inte_num' => date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT),
                    'inte_order_num' => $order_id
                ];
                Db::table('up_integral')->insert($integral);
        
                Db::commit();
                return json(['status' => 200, 'msg' => $order_id, 'price' => $order['order_total_price'], 'sy_price' => $update_price['user_recharge_balance']]);
            }catch(\Exception $e){
                Db::rollback();
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        }else{
            return json(['status' => 0, 'msg' => '请勿重复提交']);
        }
        
    }
    
    /**
     * 确认收货
     * @return \think\response\Json
     * order_id    订单ID
     */
    public function affirmOrder(){
        $order_id = input('order_id');
        $order_status = Db::table('up_order')->where('order_id', $order_id)->value('order_status');
        if($order_status != 3) return json(['status' => 0, 'msg' => '订单状态异常']);
        $res = Db::table('up_order')
            ->where('order_id', $order_id)
            ->update(['order_status' => 4, 'order_over_time' => $this->create_time]);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 订单列表页付款信息显示
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function showUnpayOrder(){
        $order_id = input('order_id');
        $order = Db::table('up_order')
            ->where('order_id', $order_id)
            ->field('order_create_time, order_total_price')
            ->find();
        return json(['status' => 200, 'msg' => $order, 'now' => time()]);
    }
    
    /**
     * 订单详情
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function orderDetail(){
        $order_id = input('order_id');
        $order = Db::table('up_order')
            ->join('up_user_address', 'addr_id = order_addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->where('order_id', $order_id)
            ->field('order_id, order_number, order_total_price, order_total_num, order_remark, 
            order_addr_id, order_status, order_create_time, order_pay_time, order_send_time, order_over_time, 
            order_cancel_time, order_close_time, u1.district sheng, u2.district shi, u3.district qu, 
            addr_address order_address, addr_user_name order_receive_username, addr_user_phone order_receive_phone, 
            addr_sheng order_sheng, addr_shi order_shi, addr_qu order_qu, order_cancel_reason')
            ->find();
        $order['order_goods'] = Db::table('up_order_info')
            ->where('oi_order_id', $order['order_id'])
            ->field('oi_goods_id, oi_goods_price, oi_num, oi_goods_thumb, oi_goods_name, oi_goods_spec')
            ->select();
        // 收货地址
//        $where['addr_id'] = $order['order_addr_id'];
//        $order['address'] = $this->address(2, $where);
        return json(['status' => 200, 'msg' => $order]);
    }
    
    /**
     * 物流
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function wuLiu(){
        $order_id = input('order_id');
        // 订单
        $order = Db::table('up_order')
            ->join('up_user_address', 'addr_id = order_addr_id', 'LEFT')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->field('order_express_company, order_express_code, order_addr_id, order_number, order_create_time, 
            order_pay_time, u1.district sheng, u2.district shi, u3.district qu, addr_address order_address, 
            addr_user_name order_receive_username, addr_user_phone order_receive_phone, addr_sheng order_sheng, 
            addr_shi order_shi, addr_qu order_qu')
            ->where('order_id', $order_id)
            ->find();
        // 收货信息
//        $address = $this->address(2, ['addr_id' => $order['order_addr_id']]);
            
        // 物流信息
        $code = ltrim($order['order_express_code'], ',');
        $order['order_express_code'] = $code;
        //*********** 获取快递公司编码
        $auto_url = 'http://www.kuaidi100.com/autonumber/auto?';
        $auto_data = [
            'num' => $code,
            'key' => config('kd.zhnkey')
        ];
        $auto_data = http_build_query($auto_data);
        $auto_url_http = $auto_url . $auto_data;
        $request_auto = kd_http($auto_url_http); // 智能判断返回的数据
        if(isset($request_auto['returnCode'])){
            return json(['status' => 0, 'msg' => $request_auto['message']]);
        }else{
            //***************** 获取快递信息
            $search_url = 'http://poll.kuaidi100.com/poll/query.do';
            
            $post_data = [];
            $post_data["customer"] = config('kd.customer');
            $key = config('kd.key');
            if(!empty($request_auto)){
                $com = $request_auto[0]['comCode'];
                $post_data["param"] = '{"com":"' . $com . '","num":"' . $code . '"}';
                $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
                $post_data["sign"] = strtoupper($post_data["sign"]);
                $post_data = http_build_query($post_data);
                $search_data = kd_http($search_url, $post_data);
                // 返回失败信息
                if(isset($search_data['returnCode'])){
                    return json(['status' => 0, 'msg' => $search_data['message'], 'order' => $order/*, 'address' => $address*/]);
                }else{
                    return json(['status' => 200, 'msg' => $search_data['data'], 'order' => $order/*, 'address' => $address*/]);
                }
            }else{
                return json(['status' => 200, 'msg' => [], 'order' => $order/*, 'address' => $address*/]);
            }
        }
    }
    
    /**
     * 注销
     * @return \think\response\Json
     */
    public function freezeUser(){
        $res = Db::table('up_u_user')->where('user_id', $this->user_id)->update(['user_status' => 2]);
        if($res){
            return json(['status' => 200, 'msg' => '注销成功']);
        }else{
            return json(['status' => 0, 'msg' => '注销失败']);
        }
        
    }
    
    /**
     * 修改密码-验证手机号
     * @return \think\response\Json
     * phone       手机号
     * code        验证码
     */
    public function checkPhone(){
        $phone = input('phone');
        $code = trim(input('code'), ' ');
        
        if(empty($code)) return json(['status' => 0, 'msg' => '请填写验证码']);
        
        // 验证码
        $yzm = Db::table('up_phonecode')->where('phone', $phone)->order('time desc')->find();
        if($code != $yzm['code']) return json(['status' => 0, 'msg' => '验证码错误']);
        // 5分钟超时
        $now = time();
        if($now - $yzm['time'] >= 301) return json(['status' => 0, 'msg' => '验证码失效']);
        if($yzm['status'] == 1) return json(['status' => 0, 'msg' => '验证码已使用']);
        
        Db::table('up_phonecode')->where('phone',$phone)->update(['status' => 1]);
        return json(['status' => 200, 'msg' => true]);
    }
    
    /**
     * 修改密码-确认新密码
     * @return \think\response\Json
     * f_pwd    新密码
     * s_pwd    确认新密码
     */
    public function updatePwd(){
        $f_pwd = input('f_pwd');
        $s_pwd = input('s_pwd');
    
        if(!$f_pwd) return json(['status' => 0, 'msg' => '请填写新密码']);
        if(!$s_pwd) return json(['status' => 0, 'msg' => '请确认新密码']);
        if($f_pwd != $s_pwd) return json(['status' => 0, 'msg' => '两次输入的密码不一致']);
    
        $update = [
            'user_password' => md5($f_pwd),
            'user_password_see' => $f_pwd,
            'user_update_time' => date('Y-m-d H:i:s')
        ];
        $res = Db::table('up_u_user')->where('user_id', $this->user_id)->update($update);
        if($res){
            return json(['status' => 200, 'msg' => '重置成功']);
        }else{
            return json(['status' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }

    //*************************************  脖脸皮商品出入库  start   ***********************************//

    /**
     * 用户是否有出库/入库权限
     * @return \think\response\Json
     */
    public function stockRole(){
        $role = Db::table('up_u_user')->where('user_id', $this->user_id)->value('user_stock_role');
        return json(['status' => 200, 'msg' => $role]);
    }

    /**
     * 根据产品码获取商品信息
     * product_code     产品码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGoodsByProductCode(){
        $product_code = input('product_code');
        $goods = Db::table('up_bo_goods')
            ->where('bg_product_code', $product_code)
            ->field('bg_id, bg_name')
            ->find();
        if($goods){
            return json(['status' => 200, 'msg' => $goods]);
        }else{
            return json(['status' => 0, 'msg' => '产品码对应的商品不存在']);
        }
    }

    /**
     * 判断编号是否已入库
     * code    防伪码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkFWCodeIn(){
        $code = input('code');
        $in = Db::table('up_bo_goods_stock_info')->where('fw_code', $code)->find();
        if($in){
            return json(['status' => 0, 'msg' => '重复入库']);
        }else{

            return json(['status' => 200, 'msg' => true]);
        }
    }

    /**
     * 脖脸皮商品入库
     * goods_id       脖脸皮商品ID
     * code           产品码
     * fw_code        防伪码，以逗号隔开
     * type           1 扫码    2 NFC
     * @return \think\response\Json
     */
    public function stockIn(){
        $goods_id = input('goods_id');
        $code = input('code');
        $type = input('type');
        $fw_code = input('fw_code');

        if(!$goods_id) return json(['code' => 100, 'msg' => '商品有误']);
        if(!$code) return json(['code' => 100, 'msg' => '请录入产品码']);
        if(!$fw_code) return json(['code' => 100, 'msg' => '请录入防伪码']);

        $fw_bar_code = explode(',', $fw_code);
        $fw_bar_code = array_filter($fw_bar_code); // 去掉空数组
        $fw_bar_code = array_unique($fw_bar_code); // 去重

        $haveIn = Db::table('up_bo_goods_stock')->where('gs_bar_code', $code)->find();

        Db::startTrans();
        try{
            // 入库
            if(!$haveIn){
                $gs_id = Db::table('up_bo_goods_stock')->insertGetId([
                    'gs_goods_id' => $goods_id,
                    'gs_bar_code' => $code,
                    'gs_time' => date('Y-m-d H:i:s')
                ]);
            }else{
                $gs_id = $haveIn['gs_id'];
            }

            // 防伪码
            $insert = [];
            foreach($fw_bar_code as $k => $v){
                $insert[$k] = [
                    'stock_id' => $gs_id,
                    'fw_code' => $v,
                    'goods_id' => $goods_id,
                    'time' => date('Y-m-d H:i:s'),
                    'type' => $type
                ];
            }
            Db::table('up_bo_goods_stock_info')->insertAll($insert);

            Db::commit();
            return json(['status' => 200, 'msg' => '录入成功']);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getLine() . ':' . $e->getMessage()]);
        }
    }

    /**
     * 出库用户
     * keyword    搜索关键字
     * page       页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function stockOutUser(){
        $keyword = input('keyword');
        $where['user_status'] = 1;
        $where['user_private_worker'] = 1;
        $where['user_rule'] = [['=', 3], ['=', '2,3'], 'or'];
        if($keyword){
            $where['user_real_name|user_shop_name'] = ['like', '%' . $keyword . '%'];
        }
        $user = Db::table('up_u_user')
            ->where($where)
            ->field('user_real_name user_username, user_id, user_shop_name, user_phone')
            ->page($this->page, 10)
            ->select();
        if($user){
            return json(['status' => 200, 'msg' => $user]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 出库时判断编码
     * fw_code     防伪码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkFWCodeOut(){
        $fw_code = input('fw_code');
        $stock_id = Db::table('up_bo_goods_stock_info')->where('fw_code', $fw_code)->value('stock_id');
        if(!$stock_id) return json(['status' => 0, 'msg' => '该防伪码暂未入库']);
//        $out = Db::table('up_bo_goods_stock_out')->where('so_fw_code', $fw_code)->find();
//        if($out) return json(['status' => 0, 'msg' => '该防伪码已出库']);
        return json(['status' => 200, 'msg' => true]);
    }

    /**
     * 出库
     * so_user_id      出库对象ID
     * fw_code         防伪码，逗号隔开
     * @return \think\response\Json
     */
    public function stockOut(){
        $so_user_id = input('so_user_id');
        $fw_code = input('fw_code');

        if(!$so_user_id) return json(['code' => 100, 'msg' => '请选择出货对象']);
        if(!$fw_code) return json(['code' => 100, 'msg' => '请录入防伪码']);

        $fw_bar_code = explode(',', $fw_code);
        $fw_bar_code = array_filter($fw_bar_code); // 去掉空数组
        $fw_bar_code = array_unique($fw_bar_code); // 去重

        $data = Db::table('up_bo_goods_stock_info')
            ->join('up_bo_goods_stock', 'gs_id = stock_id', 'LEFT')
            ->where('fw_code', 'IN', $fw_bar_code)
            ->field('goods_id, fw_code, gs_bar_code')
            ->select();

        $insert = [];
        foreach ($fw_bar_code as $k => $v){
            $insert[$k] = [
                'so_user_id' => $so_user_id,
                'so_fw_code' => $v,
                'so_time' => date('Y-m-d H:i:s')
            ];
            foreach ($data as $ke => $vo){
                if($vo['fw_code'] == $v){
                    $insert[$k]['so_goods_id'] = $vo['goods_id'];
                    $insert[$k]['so_bar_code'] = $vo['gs_bar_code'];
                }
            }
        }

        Db::startTrans();
        try{
            // 入出库表
            Db::table('up_bo_goods_stock_out')->insertAll($insert);

            // 从库存列表删除
            Db::table('up_bo_goods_stock_info')->where('fw_code', 'IN', $fw_bar_code)->delete();

            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功']);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    //*************************************  脖脸皮商品出入库  end   ***********************************//

    //********************************* 脖脸皮商品盘店 start *********************************//
    /**
     * 盘店记录
     * page    页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function myPanListB(){
        // 60天前
        $days_ago = date('Y-m-d', strtotime('-60 days'));

        $list = Db::table('up_bo_goods_pan')
            ->join('up_u_user', 'user_id = bgp_user_id', 'LEFT')
            ->where('bgp_date', '>=', $days_ago)
            ->where('bgp_teacher_id', $this->user_id)
            ->field('bgp_id, bgp_date, user_shop_name, bgp_user_id')
            ->order('bgp_date desc')
            ->page($this->page, 10)
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 选择盘店用户
     * choose_user_id      用户ID
     * @return \think\response\Json
     */
    public function chooseUser(){
        $choose_user_id = input('choose_user_id');
        $date = date('Y-m-d');
        $insert = [
            'bgp_user_id' => $choose_user_id,
            'bgp_teacher_id' => $this->user_id,
            'bgp_date' => $date
        ];
        $bgp_id = Db::table('up_bo_goods_pan')->insertGetId($insert);
        if($bgp_id){
            return json(['status' => 200, 'msg' => $bgp_id]);
        }else{
            return json(['status' => 0, 'msg' => '系统错误，请稍后重试']);
        }
    }

    /**
     * 店铺的所有商品
     * choose_user_id     选择的用户
     * bgp_id             记录ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shopAllGoods(){
        $choose_user_id = input('choose_user_id');
        $bgp_id = input('bgp_id');

        $query1 = Db::table('up_bo_goods_stock_out')
            ->join('up_bo_goods', 'so_goods_id = bg_id', 'LEFT')
            ->where('so_user_id', $choose_user_id)
            ->field('bg_name, so_goods_id')
            ->group('so_goods_id')
            ->buildSql();
        $query2 = Db::table('up_bo_goods_pan_info')
            ->where('bgpi_bgp_id', $bgp_id)
            ->field('bgpi_in_number, bgpi_out_number, bgpi_goods_id')
            ->buildSql();
        $data = Db::table([$query1 => 'a'])
            ->join([$query2 => 'b'], 'so_goods_id = bgpi_goods_id', 'LEFT')
            ->field('bgpi_in_number, bgpi_out_number, so_goods_id, bg_name')
            ->select();
        if($data){
            foreach ($data as $k => $v){
                if(!$v['bgpi_in_number'] && !$v['bgpi_out_number']){
                    $data[$k]['bgpi_in_number'] = 0;
                    $data[$k]['bgpi_out_number'] = 0;
                    $data[$k]['sale_number'] = 0;
                }elseif ($v['bgpi_in_number'] && !$v['bgpi_out_number']){
                    $data[$k]['bgpi_out_number'] = 0;
                    $data[$k]['sale_number'] = 0;
                }elseif (!$v['bgpi_in_number'] && $v['bgpi_out_number']){
                    $data[$k]['bgpi_in_number'] = 0;
                    $data[$k]['sale_number'] = 0;
                }else{
                    $data[$k]['sale_number'] = $v['bgpi_in_number'] - $v['bgpi_out_number'];
                }
            }
            return json(['status' => 200, 'msg' => $data]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 已盘店商品
     * bgp_id  记录ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function alreadyPanGoods(){
        $bgp_id = input('bgp_id');
        $data = Db::table('up_bo_goods_pan_info')
            ->join('up_bo_goods', 'bgpi_goods_id = bg_id', 'LEFT')
            ->where('bgpi_bgp_id', $bgp_id)
            ->field('bgpi_in_number, bgpi_out_number, bg_name')
            ->page($this->page, 10)
            ->select();
        if($data){
            foreach ($data as $k => $v){
                if($v['bgpi_out_number'] == 0){
                    $data[$k]['sale_number'] = 0;
                }else{
                    $data[$k]['sale_number'] = $v['bgpi_in_number'] - $v['bgpi_out_number'];
                }

            }
            return json(['status' => 200, 'msg' => $data]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 扫码盘店
     * @return \think\response\Json
     * fw_code        防伪码
     * user_other     被盘店铺用户ID
     * pan_type       1 到店   2 离店
     * bgp_id         记录ID
     */
    public function panShop(){
        $fw_code = input('fw_code');
        $user_other = input('user_other');
        $pan_type = input('pan_type');
        $bgp_id = input('bgp_id');

        $exist = Db::table('up_bo_goods_stock_out')->where('so_fw_code', $fw_code)->find();
        if(!$exist) return json(['status' => 0, 'msg' => '该编号尚未出库']);

        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_teacher')->find();
        if($user['user_teacher'] == 1) return json(['status' => 0, 'msg' => '不是内部老师，暂无扫码权限']);

        $pan = Db::table('up_bo_goods_stock_pan')
            ->where(['sp_bgp_id' => $bgp_id, 'sp_fw_bar_code' => $fw_code, 'sp_type' => $pan_type])
            ->find();
        if($pan) return json(['status' => 0, 'msg' => '重复扫码']);

        $have_in = Db::table('up_bo_goods_pan_info')
            ->where(['bgpi_bgp_id' => $bgp_id, 'bgpi_goods_id' => $exist['so_goods_id']])
            ->find();

        $data = [
            'sp_bgp_id' => $bgp_id,
            'sp_bar_code' => $exist['so_bar_code'],
            'sp_fw_bar_code' => $fw_code,
            'sp_old_user_id' => $exist['so_user_id'],
            'sp_now_user_id' => $user_other,
            'sp_pan_user_id' => $this->user_id,
            'sp_goods_id' => $exist['so_goods_id'],
            'sp_type' => $pan_type,
            'sp_date' => date('Y-m-d'),
            'sp_time' => $this->create_time
        ];
        Db::startTrans();
        try{
            // 盘店记录明细
            Db::table('up_bo_goods_stock_pan')->insert($data);

            // 已盘记录
            if($have_in){
                $query = Db::table('up_bo_goods_pan_info')
                    ->where('bgpi_id', $have_in['bgpi_id']);
                if($pan_type == 1){
                    $query->update(['bgpi_in_number' => $have_in['bgpi_in_number'] + 1]);
                }else{
                    $query->update(['bgpi_out_number' => $have_in['bgpi_out_number'] + 1]);
                }
            }else{
                $query = Db::table('up_bo_goods_pan_info');
                if($pan_type == 1){
                    $query->insert(['bgpi_bgp_id' => $bgp_id, 'bgpi_goods_id' => $exist['so_goods_id'], 'bgpi_in_number' => 1, 'bgpi_out_number' => 0]);
                }else{
                    $query->update(['bgpi_bgp_id' => $bgp_id, 'bgpi_goods_id' => $exist['so_goods_id'], 'bgpi_in_number' => 0, 'bgpi_out_number' => 1]);
                }
            }
            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功', 'goods_id' => $exist['so_goods_id']]);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    //********************************* 脖脸皮商品盘店 end   *********************************//

    //*************************************  花样青青商品出入库  start   ***********************************//

    /**
     * 根据产品码获取商品信息
     * product_code     产品码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGoodsByProductCode_h(){
        $product_code = input('product_code');
        $goods = Db::table('up_bo_goods')
            ->where('bg_product_code', $product_code)
            ->field('bg_id, bg_name')
            ->find();
        if($goods){
            return json(['status' => 200, 'msg' => $goods]);
        }else{
            return json(['status' => 0, 'msg' => '产品码对应的商品不存在']);
        }
    }

    /**
     * 判断防伪码是否已入库
     * code    防伪码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkFWCodeIn_h(){
        $code = input('code');
        $in = Db::table('up_goods_stock_info')->where('fw_code', $code)->find();
        if($in){
            return json(['status' => 0, 'msg' => '该防伪码重复入库']);
        }else{
            return json(['status' => 200, 'msg' => true]);
        }
    }

    /**
     * 花样青青商品入库
     * goods_id       花样青青商品ID
     * code           产品码
     * fw_code        防伪码，以逗号隔开
     * type           1 扫码    2 NFC
     * @return \think\response\Json
     */
    public function stockIn_h(){
        $goods_id = input('goods_id');
        $code = input('code');
        $fw_code = input('fw_code');
        $type = input('type');

        if(!$goods_id) return json(['code' => 100, 'msg' => '商品有误']);
        if(!$code) return json(['code' => 100, 'msg' => '请录入产品码']);
        if(!$fw_code) return json(['code' => 100, 'msg' => '请录入防伪码']);

        $fw_bar_code = explode(',', $fw_code);
        $fw_bar_code = array_filter($fw_bar_code); // 去掉空数组
        $fw_bar_code = array_unique($fw_bar_code); // 去重

        $haveIn = Db::table('up_goods_stock')->where('gs_bar_code', $code)->find();

        Db::startTrans();
        try{
            // 入库
            if(!$haveIn){
                $gs_id = Db::table('up_goods_stock')->insertGetId([
                    'gs_goods_id' => $goods_id,
                    'gs_bar_code' => $code,
                    'gs_time' => date('Y-m-d H:i:s')
                ]);
            }else{
                $gs_id = $haveIn['gs_id'];
            }

            // 防伪码
            $insert = [];
            foreach($fw_bar_code as $k => $v){
                $insert[$k] = [
                    'stock_id' => $gs_id,
                    'fw_code' => $v,
                    'goods_id' => $goods_id,
                    'time' => date('Y-m-d H:i:s'),
                    'type' => $type
                ];
            }
            Db::table('up_goods_stock_info')->insertAll($insert);

            Db::commit();
            return json(['status' => 200, 'msg' => '录入成功']);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getLine() . ':' . $e->getMessage()]);
        }
    }

    /**
     * 出库用户
     * keyword    搜索关键字
     * page       页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function stockOutUser_h(){
        $keyword = input('keyword');
        $where['user_status'] = 1;
        $where['user_private_worker'] = 1;
        $where['user_rule'] = [['=', 3], ['=', '2,3'], 'or'];
        if($keyword){
            $where['user_real_name|user_shop_name'] = ['like', '%' . $keyword . '%'];
        }
        $user = Db::table('up_u_user')
            ->where($where)
            ->field('user_real_name user_username, user_id, user_shop_name, user_phone')
            ->page($this->page, 10)
            ->select();
        if($user){
            return json(['status' => 200, 'msg' => $user]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 出库时判断防伪码
     * fw_code     防伪码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkFWCodeOut_h(){
        $fw_code = input('fw_code');
        $stock_id = Db::table('up_goods_stock_info')->where('fw_code', $fw_code)->value('stock_id');
        if(!$stock_id) return json(['status' => 0, 'msg' => '该防伪码暂未入库']);
//        $out = Db::table('up_goods_stock_out')->where('so_fw_code', $fw_code)->find();
//        if($out) return json(['status' => 0, 'msg' => '该防伪码已出库']);
        return json(['status' => 200, 'msg' => true]);
    }

    /**
     * 出库
     * so_user_id      出库对象ID
     * fw_code         防伪码，逗号隔开
     * @return \think\response\Json
     */
    public function stockOut_h(){
        $so_user_id = input('so_user_id');
        $fw_code = input('fw_code');

        if(!$so_user_id) return json(['code' => 100, 'msg' => '请选择出货对象']);
        if(!$fw_code) return json(['code' => 100, 'msg' => '请录入防伪码']);

        $fw_bar_code = explode(',', $fw_code);
        $fw_bar_code = array_filter($fw_bar_code); // 去掉空数组
        $fw_bar_code = array_unique($fw_bar_code); // 去重

        $data = Db::table('up_goods_stock_info')
            ->join('up_goods_stock', 'gs_id = stock_id', 'LEFT')
            ->where('fw_code', 'IN', $fw_bar_code)
            ->field('goods_id, fw_code, gs_bar_code')
            ->select();

        $insert = [];
        foreach ($fw_bar_code as $k => $v){
            $insert[$k] = [
                'so_user_id' => $so_user_id,
                'so_fw_code' => $v,
                'so_time' => date('Y-m-d H:i:s')
            ];
            foreach ($data as $ke => $vo){
                if($vo['fw_code'] == $v){
                    $insert[$k]['so_goods_id'] = $vo['goods_id'];
                    $insert[$k]['so_bar_code'] = $vo['gs_bar_code'];
                }
            }
        }

        Db::startTrans();
        try{
            // 入出库表
            Db::table('up_goods_stock_out')->insertAll($insert);

            // 从库存列表删除
            Db::table('up_goods_stock_info')->where('fw_code', 'IN', $fw_bar_code)->delete();

            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功']);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    //*************************************  花样青青商品出入库  end   ***********************************//

    //********************************* 花样青青商品盘店 start *********************************//
    /**
     * 盘店记录
     * page    页码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function myPanListH(){
        // 60天前
        $days_ago = date('Y-m-d', strtotime('-60 days'));

        $list = Db::table('up_goods_pan')
            ->join('up_u_user', 'user_id = gp_user_id', 'LEFT')
            ->where('gp_date', '>=', $days_ago)
            ->where('gp_teacher_id', $this->user_id)
            ->field('gp_id, gp_date, user_shop_name, gp_user_id')
            ->order('gp_date desc')
            ->page($this->page, 10)
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 选择盘店用户
     * choose_user_id      用户ID
     * @return \think\response\Json
     */
    public function chooseUser_h(){
        $choose_user_id = input('choose_user_id');
        $date = date('Y-m-d');
        $insert = [
            'gp_user_id' => $choose_user_id,
            'gp_teacher_id' => $this->user_id,
            'gp_date' => $date
        ];
        $gp_id = Db::table('up_goods_pan')->insertGetId($insert);
        if($gp_id){
            return json(['status' => 200, 'msg' => $gp_id]);
        }else{
            return json(['status' => 0, 'msg' => '系统错误，请稍后重试']);
        }
    }

    /**
     * 店铺的所有商品
     * choose_user_id     选择的用户
     * gp_id             记录ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function shopAllGoods_h(){
        $choose_user_id = input('choose_user_id');
        $gp_id = input('gp_id');

        $query1 = Db::table('up_goods_stock_out')
            ->join('up_bo_goods', 'so_goods_id = bg_id', 'LEFT')
            ->where('so_user_id', $choose_user_id)
            ->field('bg_name, so_goods_id')
            ->group('so_goods_id')
            ->buildSql();
        $query2 = Db::table('up_goods_pan_info')
            ->where('gpi_gp_id', $gp_id)
            ->field('gpi_in_number, gpi_out_number, gpi_goods_id')
            ->buildSql();
        $data = Db::table([$query1 => 'a'])
            ->join([$query2 => 'b'], 'so_goods_id = gpi_goods_id', 'LEFT')
            ->field('gpi_in_number, gpi_out_number, so_goods_id, bg_name')
            ->select();
        if($data){
            foreach ($data as $k => $v){
                if(!$v['gpi_in_number'] && !$v['gpi_out_number']){
                    $data[$k]['gpi_in_number'] = 0;
                    $data[$k]['gpi_out_number'] = 0;
                    $data[$k]['sale_number'] = 0;
                }elseif ($v['gpi_in_number'] && !$v['gpi_out_number']){
                    $data[$k]['gpi_out_number'] = 0;
                    $data[$k]['sale_number'] = 0;
                }elseif (!$v['gpi_in_number'] && $v['gpi_out_number']){
                    $data[$k]['gpi_in_number'] = 0;
                    $data[$k]['sale_number'] = 0;
                }else{
                    $data[$k]['sale_number'] = $v['gpi_in_number'] - $v['gpi_out_number'];
                }
            }
            return json(['status' => 200, 'msg' => $data]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 已盘店商品
     * gp_id  记录ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function alreadyPanGoods_h(){
        $gp_id = input('gp_id');
        $data = Db::table('up_goods_pan_info')
            ->join('up_bo_goods', 'gpi_goods_id = bg_id', 'LEFT')
            ->where('gpi_gp_id', $gp_id)
            ->field('gpi_in_number, gpi_out_number, bg_name')
            ->page($this->page, 10)
            ->select();
        if($data){
            foreach ($data as $k => $v){
                if($v['gpi_out_number'] == 0){
                    $data[$k]['sale_number'] = 0;
                }else{
                    $data[$k]['sale_number'] = $v['gpi_in_number'] - $v['gpi_out_number'];
                }

            }
            return json(['status' => 200, 'msg' => $data]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 扫码盘店
     * @return \think\response\Json
     * fw_code           防伪码
     * user_other     被盘店铺用户ID
     * pan_type       1 到店   2 离店
     * gp_id         记录ID
     */
    public function panShop_h(){
        $fw_code = input('fw_code');
        $user_other = input('user_other');
        $pan_type = input('pan_type');
        $gp_id = input('gp_id');

        $exist = Db::table('up_goods_stock_out')->where('so_fw_code', $fw_code)->find();
        if(!$exist) return json(['status' => 0, 'msg' => '该防伪码尚未出库']);

        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_teacher')->find();
        if($user['user_teacher'] == 1) return json(['status' => 0, 'msg' => '不是内部老师，暂无扫码权限']);

        $pan = Db::table('up_goods_stock_pan')
            ->where(['sp_gp_id' => $gp_id, 'sp_fw_bar_code' => $fw_code, 'sp_type' => $pan_type])
            ->find();
        if($pan) return json(['status' => 0, 'msg' => '重复扫码']);

        $have_in = Db::table('up_goods_pan_info')
            ->where(['gpi_gp_id' => $gp_id, 'gpi_goods_id' => $exist['so_goods_id']])
            ->find();


        $data = [
            'sp_gp_id' => $gp_id,
            'sp_bar_code' => $exist['so_bar_code'],
            'sp_fw_bar_code' => $fw_code,
            'sp_old_user_id' => $exist['so_user_id'],
            'sp_now_user_id' => $user_other,
            'sp_pan_user_id' => $this->user_id,
            'sp_goods_id' => $exist['so_goods_id'],
            'sp_type' => $pan_type,
            'sp_date' => date('Y-m-d'),
            'sp_time' => $this->create_time
        ];
        Db::startTrans();
        try{
            // 盘店记录明细
            Db::table('up_goods_stock_pan')->insert($data);

            // 已盘记录
            if($have_in){
                $query = Db::table('up_goods_pan_info')
                    ->where('gpi_id', $have_in['gpi_id']);
                if($pan_type == 1){
                    $query->update(['gpi_in_number' => $have_in['gpi_in_number'] + 1]);
                }else{
                    $query->update(['gpi_out_number' => $have_in['gpi_out_number'] + 1]);
                }
            }else{
                $query = Db::table('up_goods_pan_info');
                if($pan_type == 1){
                    $query->insert(['gpi_gp_id' => $gp_id, 'gpi_goods_id' => $exist['so_goods_id'], 'gpi_in_number' => 1, 'gpi_out_number' => 0]);
                }else{
                    $query->update(['gpi_gp_id' => $gp_id, 'gpi_goods_id' => $exist['so_goods_id'], 'gpi_in_number' => 0, 'gpi_out_number' => 1]);
                }
            }
            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功', 'goods_id' => $exist['so_goods_id']]);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }

    //********************************* 花样青青盘店 end   *********************************//

    //********************************* 我的系统列表  start *******************************//
    /**
     * 我的系统
     * keyword   搜索关键字
     * page      页码
     * type      1 团队长  2 县级管理  3 市级管理  4 省级管理
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function mySystemList(){
        $type = input('type'); // 1 团队长  2 县级管理   3 市级管理   4 省级管理
        $keyword = input('keyword');
        $user = Db::table('up_u_user')
            ->where('user_id', $this->user_id)
            ->field('user_tz_code, user_status, user_bo_role, user_teamer_status, user_agency_sheng, 
            user_agency_sheng_status, user_agency_shi, user_agency_shi_status, user_agency_qu, 
            user_agency_qu_status')
            ->find();
        $where['user_bo_role'] = ['BETWEEN', [3, 4]];
        if($keyword) $where['user_real_name'] = ['LIKE', '%' . $keyword . '%'];
        if($type == 1){
            if($user['user_tz_code'] == -1){
                return json(['status' => 200, 'msg' => []]);
            }else{
                $where['user_up_tz_code'] = $user['user_tz_code'];
            }
        }elseif ($type == 2){
            if($user['user_agency_qu'] == 0){
                return json(['status' => 200, 'msg' => []]);
            }else{
                $where['user_qu'] = $user['user_agency_qu'];
            }
        }elseif ($type == 3){
            if($user['user_agency_shi'] == 0){
                return json(['status' => 200, 'msg' => []]);
            }else{
                $where['user_shi'] = $user['user_agency_shi'];
            }
        }else{
            if($user['user_agency_sheng'] == 0){
                return json(['status' => 200, 'msg' => []]);
            }else{
                $where['user_sheng'] = $user['user_agency_sheng'];
            }
        }

        $lists = Db::table('up_u_user')
            ->field([
                'user_id',
                'user_real_name',
                'user_status',
                'user_agency_qu_status',
                'user_agency_shi_status',
                'user_agency_sheng_status',
                'user_teamer_status',
                'user_bo_district_role',
                'user_bo_role'
            ])
            ->where($where)
            ->page($this->page, 20)
            ->select();
        if($lists){
//            foreach ($lists as $k => $v){
//                // 代理状态
//                $sheng_status = '/';
//                $shi_status = '/';
//                $qu_status = '/';
//                if(strpos($v['user_bo_district_role'], ',2,') !== false){
//                    $qu_status = $v['user_agency_qu_status'] == 1 ? '启用' : '冻结';
//                }
//                if(strpos($v['user_bo_district_role'], ',3,') !== false){
//                    $shi_status = $v['user_agency_shi_status'] == 1 ? '启用' : '冻结';
//                }
//                if(strpos($v['user_bo_district_role'], ',4,') !== false){
//                    $sheng_status = $v['user_agency_sheng_status'] == 1 ? '启用' : '冻结';
//                }
//                $lists[$k]['qu_status'] = $qu_status;
//                $lists[$k]['shi_status'] = $shi_status;
//                $lists[$k]['sheng_status'] = $sheng_status;
//
//                // 团队长状态
//                $teamer_status = '/';
//                if($v['user_bo_role'] == 4){
//                    $teamer_status = $v['user_teamer_status'] == 1 ? '启用' : '冻结';
//                }
//                $lists[$k]['user_teamer_status'] = $teamer_status;
//            }
            return json(['status' => 200, 'msg' => $lists]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    //********************************* 我的系统列表  end   ******************************//

    //****************************   公共方法   **************************//
    /**
     * 我的团队
     * @param int $type    1 列表    2 统计总积分
     * @param $my_invite   我的邀请码
     * @return false|float|int|\PDOStatement|string|\think\Collection
     */
    private function myTeam($type = 1, $my_invite){
        $query = Db::table('up_u_user')->where('user_invite_other', $my_invite)->where('user_status', 1);
        if($type == 1){ // 我的团队列表
            $data = $query->field('user_id, user_real_name')
                ->order('user_time desc')
//                ->page($this->page, 10)
                ->select();
        }else{ // 我的团队总计
            $data = $query->sum('user_total_balance');
        }
        return $data;
    }
    
    /**
     * 我的订单
     * @param int $order_status    订单状态  0 全部  1 待付款  2 待发货  3 待收货  4 已完成  5 已关闭  6 已取消
     * @param int $type            1 列表   2 统计
     * @return false|int|\PDOStatement|string|\think\Collection
     */
    private function myOrder($order_status = 0, $type = 1){
        $where['order_user_id'] = $this->user_id;
        $where['order_del'] = 1;
//        $where['order_type'] = ['IN', '1,2'];
        if($order_status != 0){
            $where['order_status'] = $order_status;
        }
        $query = Db::table('up_order')->where($where);
        if($type == 1){ // 列表
            $data = $query->field('order_id, order_number, order_total_price, order_total_num, 
            order_status, order_addr_id, order_cancel_reason, order_type, order_create_time')
                ->page($this->page, 10)
                ->order('order_create_time desc')
                ->select();
        }else{
            $data = $query->count();
        }
        return $data;
    }
    
    /**
     * 用户收货地址
     * @param int $type         1 列表    2 单条   3 统计
     * @param int $where        查询条件
     */
    private function address($type = 1, $where = []){
        $query = Db::table('up_user_address')
            ->join('up_area u1', 'u1.district_id = addr_sheng', 'LEFT')
            ->join('up_area u2', 'u2.district_id = addr_shi', 'LEFT')
            ->join('up_area u3', 'u3.district_id = addr_qu', 'LEFT')
            ->where($where)
            ->field('addr_id, addr_user_name, addr_user_phone, addr_sheng, addr_shi, addr_qu, addr_address, 
            addr_is_default, u1.district sheng, u2.district shi, u3.district qu');
        if($type == 1){
            $data = $query->order('addr_is_default asc, addr_time desc')->select();
        }elseif($type == 2){
            $data = $query->find();
        }else{
            $data = $query->count();
        }
        return $data;
    }
    
    /**
     * 根据扣款顺序，生成用户剩余积分的更新数组
     * @param $order     订单信息
     * @return array
     */
    private function decPrice($order){
//        $update_price = [
//            'user_first_balance' => $order['user_first_balance'],
//            'user_huo_balance' => $order['user_huo_balance'],
//            'user_other_balance' => $order['user_other_balance'],
//            'user_recharge_balance' => $order['user_recharge_balance']
//        ];
//        // 扣款顺序，首款>货款>其它款
//        if($order['order_total_price'] <= $order['user_first_balance']){
//            $update_price['user_first_balance'] = $order['user_first_balance'] - $order['order_total_price'];
//        }else{
//            $update_price['user_first_balance'] = 0;
//            $cha1 = $order['order_total_price'] - $order['user_first_balance'];
//            if($cha1 <= $order['user_huo_balance']){
//                $update_price['user_huo_balance'] = $order['user_huo_balance'] - $cha1;
//            }else{
//                $update_price['user_huo_balance'] = 0;
//                $cha2 = $cha1 - $order['user_huo_balance'];
//                $update_price['user_other_balance'] = $order['user_other_balance'] - $cha2;
////                if($cha2 <= $order['user_other_balance']){
////                    $update_price['user_other_balance'] = $order['user_other_balance'] - $cha2;
////                }else{
////                    return json(['status' => 0, 'msg' => '可用积分不足']);
////                }
//            }
//        }
//        $update_price['user_recharge_balance'] = $order['user_recharge_balance'] - $order['order_total_price'];
//
//        return $update_price;
    }

    //*************************************************  以下为作废的代码

    /**
     * 我的积分明细-----作废
     * @return \think\response\Json
     * inte_type   0 全部  1 充值  2 支出   3 佣金
     * page     页码
     */
    public function showIntegral(){
        $inte_type = input('inte_type'); // 0 全部   1 充值   2 支出   3 佣金
        $user_balance = Db::table('up_u_user')
            ->field('user_recharge_balance, user_total_fy_balance, user_fy_balance, user_ya_price')
            ->where('user_id', $this->user_id)
            ->find();
        // 积分明细
        $where['inte_user_id'] = $this->user_id;
        $where['inte_status'] = 1;
        if($inte_type != 0){
            if($inte_type != 3){
                $where['inte_type'] = $inte_type;
            }else{
                $where['inte_type'] = ['IN', '3,4,5,6'];
            }
        }
        $inte_info = Db::table('up_integral')
            ->join('up_withdraw', 'withdraw_inte_id = inte_id', 'LEFT')
            ->where($where)
            ->field('inte_type, inte_des, inte_number, inte_time, inte_id, withdraw_status')
            ->order('inte_time desc')
            ->page($this->page, 15)
            ->select();
        if($inte_info){
            foreach($inte_info as $k => $v){
                if($v['inte_type'] == 5){
                    // 申请转货款明细
                    $info = Db::table('up_integral_tixian_hk')
                        ->where('zhuan_inte_id', $v['inte_id'])
                        ->field('zhuan_number, zhuan_time')
                        ->order('zhuan_time desc')
                        ->select();
                    if($info){
                        $inte_info[$k]['info'] = $info;
                    }else{
                        $inte_info[$k]['info'] = [];
                    }
                    // 是否可以操作转货款
                    $withdraw = Db::table('up_withdraw')->where('withdraw_inte_id', $v['inte_id'])->field('withdraw_can_zhuan')->find();
                    $inte_info[$k]['can_do'] = $withdraw['withdraw_can_zhuan'];
                }
            }
            return json(['status' => 200, 'msg' => $user_balance, 'inte' => $inte_info]);
        }else{
            return json(['status' => 200, 'msg' => $user_balance, 'inte' => []]);
        }
    }

    /**
     * 讲申请提现的记录，部分金额转货款-----作废
     * @return \think\response\Json
     * inte_id       申请提现的记录ID
     * zhuan_number  申请转货款积分数
     */
    public function applyHuo(){
        $inte_id = input('inte_id');
        $zhuan_number = input('zhuan_number');
        // 转货款总数不能超过申请提现总数
        $inte = Db::table('up_integral')->where('inte_id', $inte_id)->field('inte_number')->find();
        $count_zhuan_number = Db::table('up_integral_tixian_hk')->where('zhuan_inte_id', $inte_id)->sum('zhuan_number');
        if($zhuan_number + $count_zhuan_number > $inte['inte_number']) return json(['status' => 0, 'msg' => '转货款总积分不能超过提现总积分']);

        $insert = [
            'zhuan_inte_id' => $inte_id,
            'zhuan_user_id' => $this->user_id,
            'zhuan_number' => $zhuan_number,
            'zhuan_time' => $this->create_time
        ];

        $user = Db::table('up_u_user')->where('user_id', $this->user_id)->field('user_total_balance, user_huo_balance')->find();
        $update_user = [
            'user_total_balance' => $user['user_total_balance'] + $zhuan_number,
            'user_huo_balance' => $user['user_huo_balance'] + $zhuan_number
        ];
        Db::startTrans();
        try{
            // 插入积分明细详情表
            Db::table('up_integral_tixian_hk')->insert($insert);

            // 更新用户总积分&货款
            Db::table('up_u_user')->where('user_id', $this->user_id)->update($update_user);

            Db::commit();
            return json(['status' => 200, 'msg' => '操作成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }

    /**
     * 提现页面展示-----作废
     * @return \think\response\Json
     */
    public function showWithdraw(){
        // 用户信息
        $user = Db::table('up_u_user')
            ->where('user_id', $this->user_id)
            ->field('user_fy_balance, user_real_name, user_phone, user_shop_name, user_bank_username, 
            user_bank_name, user_bankcard_code, user_is_perfect')
            ->find();
        // 本月第一天
        $first_day = date('Y-m-01 00:00:00');
        // 当前时间
        $now = date('Y-m-d H:i:s');
        // 当月的分佣
        $untixian = Db::table('up_integral')
            ->where([
                'inte_user_id' => $this->user_id,
                'inte_type' => 3,
                'inte_time' => ['between', [$first_day, $now]],
//                'inte_status' => 1
            ])
            ->sum('inte_number');
        // 可提现的分佣，总分佣-当月的分佣
        $can_tixian = $user['user_fy_balance'] - $untixian;
        $user['untixian'] = $untixian;
        $user['can_tixian'] = $can_tixian;
        // 提现规则
        $txRule = Db::table('up_about')->where('id', 8)->value('content');
        return json(['status' => 200, 'msg' => $user, 'rule' => $txRule]);
    }

    /**
     * 提现-----作废
     * @return \think\response\Json
     * withdraw_price     提现金额
     * withdraw_type      1  提现    2 转货款
     */
    public function withdraw(){
        $withdraw_price = input('withdraw_price');
        $withdraw_type = input('withdraw_type'); // 1 提现   2 转货款
        $withdraw_num = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);

        $user_balance = Db::table('up_u_user')
            ->where('user_id', $this->user_id)
            ->field('user_fy_balance')
            ->find();
        // 本月第一天
        $first_day = date('Y-m-01 00:00:00');
        // 当前时间
        $now = date('Y-m-d H:i:s');
        // 当月的分佣
        $untixian = Db::table('up_integral')
            ->where([
                'inte_user_id' => $this->user_id,
                'inte_type' => 3,
                'inte_time' => ['between', [$first_day, $now]],
//                'inte_status' => 1
            ])
            ->sum('inte_number');
        // 可提现的分佣，总分佣-当月的分佣
        $can_tixian = $user_balance['user_fy_balance'] - $untixian;
        if($can_tixian < $withdraw_price) return json(['status' => 0, 'msg' => '可提现佣金不足']);

        $withdraw = [
            'withdraw_user_id' => $this->user_id,
            'withdraw_type' => $withdraw_type,
            'withdraw_number' => $withdraw_num,
            'withdraw_price' => $withdraw_price,
            'withdraw_time' => $this->create_time
        ];

        $inte = [
            'inte_user_id' => $this->user_id,
            'inte_other_user_id' => 0,
//            'inte_type' => 4,
            'inte_number' => $withdraw_price,
            'inte_front' => $user_balance['user_fy_balance'],
            'inte_after' => $user_balance['user_fy_balance'] - $withdraw_price,
            'inte_time' => $this->create_time,
            'inte_num' => date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT)
        ];
        if($withdraw_type == 1){
            $inte['inte_des'] = '提现';
            $inte['inte_type'] = 5;
        }else{
            $inte['inte_des'] = '转货款';
            $inte['inte_type'] = 6;
        }

        Db::startTrans();
        try{
            // 积分明细
            $inte_id = Db::table('up_integral')->insertGetId($inte);
            // 提现
            $withdraw['withdraw_inte_id'] = $inte_id;
            Db::table('up_withdraw')->insert($withdraw);
            // 扣除佣金
            Db::table('up_u_user')->where('user_id', $this->user_id)->setDec('user_fy_balance', $withdraw_price);

            Db::commit();
            return json(['status' => 200, 'msg' => '提交成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
}